package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantPropertiesUtil;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author jiaoyanlin
 * @Date 2021/9/8 14:46
 * @Description WxApiController
 */
@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("callback")
    public String callback(String code, String state){
        //得到授权临时票据code
        //1.先获取code

        try {
            //2.拿着code和appid请求微信接口
            //第二步 拿着code和微信id和秘钥，请求微信固定地址 ，得到两个值
            //使用code和appid以及appscrect换取access_token
            //  %s   占位符
            StringBuffer baseAccessTokenUrl = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                    .append("?appid=%s")
                    .append("&secret=%s")
                    .append("&code=%s")
                    .append("&grant_type=authorization_code");
            String url = String.format(baseAccessTokenUrl.toString(),
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code);
            //HttpClient发送get请求
            String result= HttpClientUtils.get(url);
            System.out.println("result = " + result);
            //从返回字符串获取两个值 openid  和  access_token
            JSONObject jsonObject = JSONObject.parseObject(result);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            //根据openid判断数据库是否存在
            UserInfo userInfo =userInfoService.findUserByOpenid(openid);
            if (userInfo==null){
                //3 拿着openid  和  access_token请求微信地址，得到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userUrl = String.format(baseUserInfoUrl, access_token, openid);
                String userResult = HttpClientUtils.get(userUrl);
                System.out.println("userResult:"+userResult);
                //获取扫码人的昵称
                JSONObject userJson = JSONObject.parseObject(userResult);
                String nickname = userJson.getString("nickname");
                //获取扫描人信息添加数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
         //TODO返回登录需要数据



        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //返回登录二维码参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public R getLoginParam(){

        try {
            Map<String, Object> map = new HashMap<>();
            //appid
            map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
            //scope
            map.put("scope", "snsapi_login");
            //redirectUri url编码
            String redirectUri = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
            URLEncoder.encode(redirectUri,"utf-8");
            map.put("redirectUri", redirectUri);
            //可选值
            map.put("state", System.currentTimeMillis()+"");
            return R.ok().data(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return R.error();
        }
        //

    }
}
